<template>
  <div class="el-color-dropdown">
    <div class="linear-bg" :style="gradientStyle"></div>
    <div class="flex-justify-between pad-top-btm-10 pad-rgt-10">
      <el-select v-model="linearGradient.direction" placeholder="请选择方向" class="width-50" size="mini">
        <el-option v-for="(item,index) in directionData" :key="index" :label="item.label"
                   :value='item.value'></el-option>
      </el-select>
      <span class="el-icon-plus cursor-pointer font-size-18" @click="addLinearColor"></span>
    </div>
    <div class="linear-color-box">
      <div class="flex-justify-between mar-btm-10" v-for="(item,index) in linearGradient.colors" :key="index">
        <div class="flex-justify-start">
          <el-popover
            placement="left"
            trigger="manual"
            v-model="popovers[index].visible"
          >
            <span class="el-icon-close" @click="togglePopover(index)"></span>
            <div class="el-color-dropdown__main-wrapper">
              <hue-slider ref="hue" :color="color" vertical style="float: right;"></hue-slider>
              <sv-panel ref="sl" :color="color"></sv-panel>
            </div>
            <alpha-slider v-if="showAlpha" ref="alpha" :color="color" class="mar-top-10 mar-btm-10"></alpha-slider>
            <div class="el-color-dropdown__btns">
              <el-button plain size="mini" class="el-color-dropdown__btn" @click="confirmLinearValue(index)">
                {{t('el.colorpicker.confirm')}}
              </el-button>
            </div>
            <span slot="reference" class="linear-color-cont " :style="{background:item}"
                  @click="togglePopover(index)"></span>
          </el-popover>

          <el-input :value="item" size="mini" @input="updateItem($event, index)" class="width-100" clearable></el-input>
        </div>
        <span v-if="linearGradient.colors.length>2" class="el-icon-minus cursor-pointer font-size-18 pad-rgt-10"
              @click="deleteLinearColor(index)"></span>
      </div>
    </div>
    <div class="el-color-dropdown__btns">
      <el-button size="mini" type="text" class="el-color-dropdown__link-btn" @click="cancelValue">
        {{t('el.colorpicker.clear')}}
      </el-button>
      <el-button plain size="mini" class="el-color-dropdown__btn" @click="confirmValue">
        {{t('el.colorpicker.confirm')}}
      </el-button>
    </div>
  </div>
</template>

<script>
  import SvPanel from './sv-panel';
  import HueSlider from './hue-slider';
  import AlphaSlider from './alpha-slider';
  import Predefine from './predefine';
  import Popper from 'element-ui/src/utils/vue-popper';
  import Locale from 'element-ui/src/mixins/locale';
  import ElInput from 'element-ui/packages/input';
  import ElButton from 'element-ui/packages/button';
  import Theme from './theme.vue';
  import {mapState} from "vuex";
  import {formatLinearColor} from  "@/utils"

  export default {
    name: 'ElColorPickerLineardown',
    components: {
      SvPanel,
      HueSlider,
      AlphaSlider,
      ElInput,
      ElButton,
      Predefine,
      Theme
    },
    mixins: [Popper, Locale],
    props: {
      backgroundLinearGradient: {
        type: Object,
        default: () => {
          return {}
        }
      },
      // eslint-disable-next-line vue/require-prop-types
      color: {
        required: true
      },
      showAlpha: {
        type: Boolean,
        default: false
      },
      showPanelColor: {
        type: Boolean,
        default: false
      },
      predefine: {
        type: Array,
        default: () => {
          return [];
        }
      },
    },
    data() {
      return {
        customInput: '',
        direction: 'right',
        directionData: [
          {label: '从左到右', value: 'right'},
          {label: '从右到左', value: 'left'},
          {label: '从下到上', value: 'top'},
          {label: '从上到下', value: 'bottom'},
          {label: '从左下角到右上角', value: 'topRight'},
          {label: '从右下角到左上角', value: 'topLeft'},
          {label: '从左上角到右下角', value: 'bottomRight'},
          {label: '从右上角到左下角', value: 'bottomLeft'}
        ],
        linearGradient: {},
        popovers: [],
        formatLinearColor:formatLinearColor
      };
    },
    computed: {
      ...mapState({
        activeTheme: state => state.ide.activeTheme
      }),
      gradientStyle() {
        const {colors} = this.linearGradient;
        if (colors.length > 0)
          return {
            background: `linear-gradient(${this.formatLinearColor(this.linearGradient.direction)}, ${this.linearGradient.colors.join(',') || []})`
          };
      },

    },
    watch: {
      showPopper(val) {
        if (val === true) {
          this.$nextTick(() => {
            const {sl, hue, alpha} = this.$refs;
            sl && sl.update();
            hue && hue.update();
            alpha && alpha.update();
          });
        }
      },
      backgroundLinearGradient: {
        immediate: true,
        handler(val) {
          this.linearGradient = val;
          this.linearGradient.colors = Object.values(this.linearGradient.colors)
          this.popovers = this.linearGradient.colors.map(item => {
            return {visible: false};
          });
        }
      },

    },
    mounted() {
      this.$parent.popperElm = this.popperElm = this.$el;
      this.referenceElm = this.$parent.$el;

    },
    methods: {
      confirmValue() {
        this.$emit('pick', this.linearGradient);
      },
      addLinearColor() {
        this.linearGradient.colors.push(this.getRandomColor())
        this.popovers.push({visible: false})
      },
      deleteLinearColor(idx) {
        this.linearGradient.colors.splice(idx, 1)
      },
      updateItem(value, index) {
        this.$set(this.linearGradient.colors, index, value);
        this.$forceUpdate()
      },
      getRandomColor() {
        // 生成随机的十六进制颜色
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      },
      cancelValue() {
        this.linearGradient.colors = []
        this.linearGradient.direction = 'right'
        this.popovers = []
        this.$emit('clear')
      },
      togglePopover(index) {
        this.popovers.forEach((item) => {
          item.visible = false
        });
        if (index >= 0 && index < this.popovers.length) {
          this.popovers[index].visible = true;
        }
      },
      confirmLinearValue(index) {
        this.$set(this.linearGradient.colors, index, this.color.value);
        this.$forceUpdate()
        this.popovers[index].visible = !this.popovers[index].visible;
      }

    }
  };
</script>

<style scoped lang="less">
  .linear-bg {
    width: 100%;
    height: 20px;
    //linear-gradient(to right, #ffcc00, #ff6699)
    background: linear-gradient(to right, #ffcc00, #ff6699);
  }

  .el-color-picker__panel {
    position: relative !important;
    border: none !important;
    box-shadow: none !important;
  }

  .linear-color-box {
    width: 100%;

    .linear-color-cont {
      display: inline-block;
      width: 28px;
      height: 28px;
      margin-right: 10px;
    }
  }

</style>
